import { ioredis } from '@src/db'
import Users from '../user/user'
import dayjs from 'dayjs'
import { omit } from 'lodash'

/**
 * 行为状态
 */
export const actions = {
  leisure: { value: 0, name: '空闲' },
  retreat: { value: 1, name: '闭关' },
  exercise: { value: 2, name: '锻体' },
  hurry: { value: 3, name: '赶路' },
  portal: { value: 4, name: '传送' },
  duJie: { value: 5, name: '渡劫' },
  extension: { value: 6, name: '扩建' },
  fairyland: { value: 7, name: '秘境' },
  spirit: { value: 8, name: '聚灵' },
  team: { value: 9, name: '组队' },
  ectype: { value: 10, name: '副本' }
}

type ActionType = keyof typeof actions
const defaultState: ActionType =
  'leisure' /* 默认固定为[空闲]，其余状态结束后均恢复为默认状态 */

// 检测当前状态
export const getStatus = async (UID: string): Promise<ActionType> => {
  // 1. 获取对应的状态
  const data = await ioredis.get(`xiuxian:user:status:${UID}`)
  if (!data) return defaultState

  // 2. 检测是否完成某个状态
  const result = JSON.parse(data)
  if (dayjs(Date.now()).isAfter(result.endTime)) {
    // 获取用户指定数据
    const params = omit(Object.keys(result), ['state', 'startTime', 'endTime'])

    // 2.1 获取某个状态的成果
    const userData = Users.getUserInfo(UID, params)
    // params.forEach(prop => {
    //   userData[prop] += result[prop]
    // })

    // 2.2 修改回默认状态 => 空闲
    Users.updateInfo(UID, { ...userData, status: actions[defaultState].value })
    ioredis.del(`xiuxian:user:status:${UID}`)
    return defaultState
  }

  // 3. 状态还未结束 => 对应的状态
  return result?.state || defaultState
}

/**
 * 设置状态
 * @param UID [string] 用户编号
 * @param key [ActionType] 指定状态
 * @param duration [number] 状态持续时长：默认 5秒
 * @param options [unknown] 奖励 等数据
 */
type setStatusParam = {
  UID: string
  key: ActionType
  duration: number
  options: unknown
}
export const setStatus = async ({
  UID,
  key,
  duration = 5 * 1000 /* 5秒 */,
  ...options
}: setStatusParam) => {
  // 1. 判断当前条件是否空闲
  const state = await getStatus(UID)
  const { value, name } = actions[state]
  if (state != 'leisure') {
    return {
      code: 500,
      message: `该角色正处于${name}中，无法切换状态~`
    }
  }

  // 2. 设置对应的状态数据
  const result = {
    state: key,
    startTime: Date.now(),
    endTime: Date.now() + duration,
    ...options
  }
  ioredis.set(`xiuxian:user:status:${UID}`, JSON.stringify(result))

  // 3. 修改用户的状态
  Users.updateInfo(UID, { status: value })
  return { code: 200, message: `准备开始${name}`, data: result }
}
